package com.luxsoft.sw3.replica.validacion;

import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.log4j.Logger;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerListener;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.luxsoft.utils.LoggerHelper;

public class ValidacionManager {
	
	private static ValidacionManager INSTANCE;
	
	private Logger logger=LoggerHelper.getLogger();
	
	private ApplicationContext context;
	
	private ValidacionManager(){
	}
	
	protected String[] getConfigLocations() {
        return new String[] {                
        		"em2-validacion-replica.xml"        		
            };
    }
	
	public synchronized ApplicationContext getContext(){		
		if(context==null){
			context=new ClassPathXmlApplicationContext(
					getConfigLocations(),ValidacionManager.class);
		}
		return context;
	}
	
	protected synchronized void closeContext(){
		((ClassPathXmlApplicationContext)INSTANCE.getContext()).close();
		context=null;
	}
	
	public synchronized Validador getValidador(String name){
		return (Validador)getContext().getBean(name);
	}
		
	/** Tareas con el Scheduler ***/
	
	public Scheduler getScheduler(){
		return (Scheduler)context.getBean("replicaScheduler");
	}
	
	
	
	public void addSchedulerListener(SchedulerListener listener){
		try {
			getScheduler().addSchedulerListener(listener);
		} catch (SchedulerException e) {
			logger.error(ExceptionUtils.getRootCauseMessage(e),e);
		}
	}
	
	public void removeSchedulerListener(SchedulerListener listener){
		try {
			getScheduler().removeSchedulerListener(listener);
		} catch (SchedulerException e) {
			logger.error(ExceptionUtils.getRootCauseMessage(e),e);
		}
	}
	
	public void startScheduler() throws SchedulerException{
		getScheduler().start();
		
	}
	
	public void stopScheduler() throws SchedulerException{
		getScheduler().shutdown();
	}
	
	public String[] getJobs() throws SchedulerException{
		return getScheduler().getJobNames(null);
	}

	/**
	 * FactoryMethod para accesar al singleton
	 * 
	 * @return
	 */
	public static ValidacionManager getInstance(){
		if(INSTANCE==null){
			INSTANCE=new ValidacionManager();
		}
		return INSTANCE;
	}

}
